package com.jiumi.pay.controller;

import com.alibaba.fastjson2.JSON;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.OrderQueryModel;
import com.ijpay.wxpay.model.RefundModel;
import com.ijpay.wxpay.model.RefundQueryModel;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import com.jiumi.api.entity.WxPayConfig;
import com.jiumi.api.entity.WxPayIosConfig;
import com.jiumi.baseconfig.domain.BaseOrder;
import com.jiumi.baseconfig.domain.BaseUser;
import com.jiumi.baseconfig.domain.ScoreHistory;
import com.jiumi.baseconfig.service.IBaseOrderService;
import com.jiumi.baseconfig.service.IBaseUserService;
import com.jiumi.baseconfig.service.IScoreHistoryService;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.utils.DateUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.common.utils.uuid.Seq;
import com.jiumi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lun.zhang
 * @create 2022/11/21 14:29
 */
@RequestMapping("/api")
@RestController
@Slf4j
public class WxIosPayApiController {


    @Autowired
    WxPayIosConfig wxPayIosConfig;

    private String notifyUrl;
    private String refundNotifyUrl;

    @Autowired
    private IBaseOrderService baseOrderService;

    @Autowired
    private IBaseUserService userInfoService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IScoreHistoryService scoreHistoryService;


    @PostConstruct()
    public void init(){
        try {
            //如果是证书模式，放开if,
            if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
                //TODO 确认证书所在路径
                wxPayIosConfig.setCertPath("D:\\1637042361_20230113_cert\\apiclient_cert.p12");
            }
            WxPayApiConfig reqConfig = new WxPayApiConfig();
            BeanUtils.copyProperties(wxPayIosConfig,reqConfig);
            WxPayApiConfigKit.setThreadLocalWxPayApiConfig(reqConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
        notifyUrl = wxPayIosConfig.getDomain() + wxPayIosConfig.getNotifyUrl();
        refundNotifyUrl = wxPayIosConfig.getDomain() + wxPayIosConfig.getRefundNotify();
        log.info("[微信支付]:当前微信支付回调地址" + notifyUrl);
        log.info("[微信支付]:当前微信退款回调地址" + refundNotifyUrl);
    }

    /**
     * 苹果设备IOS支付
     * @param request
     * @return
     */
    @RequestMapping(value = "/noAuth/wxpay/appPayIos", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult appPayIos(HttpServletRequest request) {
        //需要通过授权来获取openId
        String outTradeNo = Seq.getId();

        String orderCode=request.getParameter("orderCode");
        String scoreAmount=request.getParameter("scoreAmount");
        int scoreNum=0;
        if(StringUtils.isNotEmpty(scoreAmount)){
            scoreNum=Integer.parseInt(scoreAmount);
        }

        BaseOrder baseOrder= baseOrderService.selectBaseOrderByOrderCode(orderCode);
        if(baseOrder==null){
            return AjaxResult.error("订单不存在");
        }
        if(!"01".equals(baseOrder.getPayStatus())){
            return AjaxResult.error("待支付状态的订单才能进行支付");
        }
        BaseUser orderUser= userInfoService.selectBaseUserByUserId(baseOrder.getUserId());
        if(orderUser.getScoreAmount().intValue()<scoreNum){
            return AjaxResult.error("您的积分不足!");
        }
        int orderAmount= baseOrder.getOrderAmount().multiply(new BigDecimal(100)).intValue();
        if(orderAmount<=0){
            return AjaxResult.error("订单金额错误");
        }
        String ip = IpKit.getRealIp(request);
        if (StringUtils.isEmpty(ip)) {
            ip = "127.0.0.1";
        }
        String percent = configService.selectConfigByKey("sys.customer.usescore.percent");
        double scorePercent=StringUtils.isNotEmpty(percent)?Double.valueOf(percent):1;
        double scoreMoney=scoreNum*scorePercent;
        if(baseOrder.getOrderAmount().doubleValue()<scoreMoney){
            return AjaxResult.error("请输入合适的积分");
        }
        baseOrder.setTradeCode(outTradeNo);
        baseOrder.setUpdateTime(DateUtils.getNowDate());
        //积分相抵
        if(baseOrder.getOrderAmount().doubleValue()==scoreMoney){
            baseOrder.setPayAmount(new BigDecimal(0));
            baseOrder.setScoreAmount(new BigDecimal(scoreNum));
            baseOrder.setPayTime(DateUtils.getNowDate());
            baseOrder.setPayStatus("02");
            baseOrderService.updateBaseOrder(baseOrder);

            BaseUser currentUser=userInfoService.selectBaseUserByUserId(baseOrder.getUserId());
            BaseUser scoreUser=new BaseUser();
            scoreUser.setUserId(baseOrder.getUserId());
            scoreUser.setScoreAmount(currentUser.getScoreAmount()-baseOrder.getScoreAmount().intValue());
            userInfoService.updateBaseUserScore(scoreUser);

            ScoreHistory refHis=new ScoreHistory();
            refHis.setUserId(currentUser.getUserId());
            refHis.setUserName(currentUser.getUserName());
            refHis.setRemark("订单抵扣积分");
            refHis.setScore(new BigDecimal(scoreNum*-1));
            refHis.setCreateTime(DateUtils.getNowDate());
            scoreHistoryService.insertScoreHistory(refHis);

            AjaxResult payResult=  AjaxResult.success("支付成功");
            payResult.put("scoreFlag",'Y');
            return payResult;
        }
        BigDecimal payAmount=baseOrder.getOrderAmount().subtract(new BigDecimal(scoreMoney)).setScale(2, RoundingMode.HALF_UP);
        System.out.println("===========================");
        System.out.println(payAmount);
        baseOrder.setPayAmount(payAmount);
        baseOrder.setScoreAmount(new BigDecimal(scoreNum));
        //实际支付金额
        int orderPayAmount=payAmount.multiply(new BigDecimal(100)).intValue();
        System.out.println(orderPayAmount);
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getApiConfig(wxPayIosConfig.getAppId());
        String nonceStr=WxPayKit.generateStr();
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(nonceStr)
                .body("让支付触手可及-家政服务APP支付")
                .attach("Node.js 版:https://jiumi.com")
                .out_trade_no(WxPayKit.generateStr())
                .total_fee(String.valueOf(orderPayAmount))
                .spbill_create_ip(ip)
                .notify_url(notifyUrl)
                .trade_type(TradeType.APP.getTradeType())
                .out_trade_no(outTradeNo)
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5);

        Map<String, String> packageParams=null;
        try{
            String xmlResult = WxPayApi.pushOrder(false, params);

            log.info(xmlResult);
            Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

            String returnCode = result.get("return_code");
            String returnMsg = result.get("return_msg");
            if (!WxPayKit.codeIsOk(returnCode)) {
                return  AjaxResult.error(returnMsg);
            }
            String resultCode = result.get("result_code");
            if (!WxPayKit.codeIsOk(resultCode)) {
                return  AjaxResult.error(returnMsg);
            }
            // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
            String prepayId = result.get("prepay_id");
            //appPrepayIdCreateSign(String appId, String partnerId, String prepayId, String partnerKey, SignType signType)
            packageParams = WxPayKit.appPrepayIdCreateSign(wxPayApiConfig.getAppId(),wxPayApiConfig.getMchId(),prepayId,wxPayApiConfig.getPartnerKey(), SignType.MD5);
            String jsonStr = JSON.toJSONString(packageParams);
            log.info("app支付的参数:" + jsonStr);
            baseOrderService.updateBaseOrder(baseOrder);
        }
        catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.error(e.getMessage());
        }

        AjaxResult payResult=  AjaxResult.success(packageParams);
        payResult.put("scoreFlag",'N');
        return payResult;
    }

}
